//
//  InitDataViewController.m
//  Molian
//
//  Created by 胡津 on 15/4/15.
//  Copyright (c) 2015年 xiaocan. All rights reserved.
//

#import "InitDataViewController.h"
#import "ZHPickView.h"
#import "UserDateEditSeriesViewController.h"
//#import "TimeUtils.h"
#import <FSMediaPicker.h>//照片选择
#import <CommonCrypto/CommonDigest.h>
#import "AppDelegate.h"
//#import "ThirdpartyPhoneViewController.h"

@interface InitDataViewController ()<UITableViewDelegate,UITableViewDataSource,ZHPickViewDelegate,UserDateEditSeriesDelegate,FSMediaPickerDelegate,UITextFieldDelegate>
//视图列表
@property (nonatomic, strong)UITableView *tableView;
@property(nonatomic,strong)NSIndexPath *indexPath;
@property(nonatomic,strong)ZHPickView *pickview;
@property (strong, nonatomic) AVFile *avatarFile;
@property (nonatomic, strong)UIImageView * userAvatarImg;

@end

@implementation InitDataViewController
{
    NSArray *titleArr;//标题数组
    NSArray *dataArr;//标题数组
    NSDate *jobdate;//时间
    BOOL bool_headimage;
    UITextField *userName;
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:YES];
    [_pickview remove];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        if (self.isThirdparty) {
//            ThirdpartyPhoneViewController *thirdPVC = [[ThirdpartyPhoneViewController alloc] init];
//            [Utils pushTabbarHidden:thirdPVC Selfvc:self];
//        }
//    });
   
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    self.view.backgroundColor = APPCOLORBACKGROUNDCOLOR(1);
    self.title = @"个人信息";
    
    NSString *location = [[NSString alloc]init];
    for (int i = 0 ; i < [self.location count]; i++) {
        if (i == [self.location count]-1) {
            location = [location stringByAppendingString:[NSString stringWithFormat:@"%@",self.location[i]]];
        }else{
            location = [location stringByAppendingString:[NSString stringWithFormat:@"%@ ",self.location[i]]];
        }
    }
    
    
    titleArr = @[@"昵称",@"性别",@"出生日期",@"城市",@"我属于"];
    dataArr = @[@"",[NSString stringWithFormat:@"%@",self.gender == 1 ? @"男": @"女"],@"",location,@"",@""];
    
    UIBarButtonItem *rightItem  = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(rightItem)];
    self.navigationItem.rightBarButtonItem = rightItem;
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, DeviceHeight)style:UITableViewStylePlain];
    self.tableView.backgroundColor = RGBA(244, 244, 244, 1);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollsToTop = YES;
    self.tableView.separatorColor = RGBA(225, 225, 225, 1);//分隔条颜色
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 30, 0);//偏移量
    self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(0, 0, 0, 0);//滚动条偏移量
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 200)];
    self.tableView.tableFooterView = [[UIView alloc] init];//不显示空的cell
    [self.view addSubview:self.tableView];
    
    //头像
    self.userAvatarImg = [[UIImageView alloc]init];
    self.userAvatarImg.image = [UIImage imageNamed:@"head"];
    self.userAvatarImg.frame = CGRectMake((DeviceWidth-90)/2, 30, 90, 90);
    self.userAvatarImg.layer.masksToBounds = YES;//开启圆角
    [self.userAvatarImg.layer setCornerRadius:CGRectGetHeight([self.userAvatarImg bounds]) / 2];
    self.userAvatarImg.userInteractionEnabled = YES;
    [self.userAvatarImg.layer setBorderColor:[[UIColor whiteColor] colorWithAlphaComponent:1].CGColor];
    [self.userAvatarImg.layer setBorderWidth:2];
    [self.userAvatarImg setContentMode:UIViewContentModeScaleAspectFill];
    [self.userAvatarImg addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backgroundPan:)]];
    MPUser *u = [MPUser currentUser];
    if(u.avatar.url){
         bool_headimage =  YES;
         [self.userAvatarImg sd_setImageWithURL:[NSURL URLWithString:u.avatar.url] placeholderImage:[UIImage imageNamed:@"common_avatar_loading_background"]];
        NSMutableArray *galleryImgs = [NSMutableArray array];
        [galleryImgs addObject:u.avatar];
        // 获取相册内容
        AVQuery *galleryQuery = [MPGallery query];
        [galleryQuery whereKey:@"belong_to" equalTo:u];
        [galleryQuery includeKey:@"images"];
        [galleryQuery getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
            MPGallery *g;;
            if (object == nil) {
                // 找不到,创建新相册
               g = [MPGallery object];
            } else {
                g = (MPGallery*)object;
            }
            g.belong_to = u;
            g.images = galleryImgs;
            [g saveInBackground];
        }];
        self.avatarFile = u.avatar;
    }else{
         bool_headimage =  NO;
    }
    
    
    [self.tableView addSubview:self.userAvatarImg];
    
    if (self.userAvatarURL) {
        [self.userAvatarImg sd_setImageWithURL:[NSURL URLWithString:self.userAvatarURL] completed:^(UIImage *image, NSError *error, EMSDImageCacheType cacheType, NSURL *imageURL) {
            float kCompressionQuality = 0.3;
            NSData *imgData = UIImageJPEGRepresentation(self.userAvatarImg.image, kCompressionQuality);
            self.avatarFile = [AVFile fileWithName:@"avatar.jpg" data:imgData];
            [self.avatarFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                [HUD hideFromViewAnimated:YES];
                if (succeeded) {
                    bool_headimage =  YES;
                    NSLog(@"save avatar succeed");
                    NSMutableArray *galleryImgs = [NSMutableArray array];
                    [galleryImgs addObject:self.avatarFile];
                    // 获取相册内容
                    AVQuery *galleryQuery = [MPGallery query];
                    [galleryQuery whereKey:@"belong_to" equalTo:u];
                    [galleryQuery includeKey:@"images"];
                    [galleryQuery getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
                        MPGallery *g = (MPGallery*)object;
                        if (!g) {
                            // 找不到,创建新相册
                            g = [MPGallery object];
                        } else {
                        }
                        g.belong_to = [MPUser currentUser];
                        g.images = galleryImgs;
                        [g saveInBackground];
                    }];                } else {
                    bool_headimage =  NO;
                    NSLog(@"save avatar failed");
                    [HUD Prompt:@"保存头像失败,请检查网络再重试"];
                    self.avatarFile = nil;
                }
                
            }];
            [HUD setOnViewWithTitle:nil animated:YES];
            
            
        }];
        
    }
    
    userName = [[UITextField alloc]initWithFrame:CGRectMake(100, 200, DeviceWidth-120, 45)];
    userName.textAlignment = NSTextAlignmentRight;
    userName.delegate  = self;
    userName.text = self.nickname;
    [self.tableView addSubview:userName];
    
   
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static  NSString *CellIdentifier = @"SettingsCell" ;
    //自定义cell类
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if  (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    }
    
    cell.textLabel.text = [titleArr objectAtIndex:indexPath.row];
    cell.detailTextLabel.text = [dataArr objectAtIndex:indexPath.row];
    
    if (indexPath.row == 1) {
        UILabel*label = [[UILabel alloc]initWithFrame:CGRectMake(50, 0, 100, 45)];
        label.text = @"(选择后不能修改)";
        label.textColor = [UIColor grayColor];
        label.font = [UIFont fontWithName:FontName size:12];
        [cell.contentView addSubview:label];
    }
    
    
    if (indexPath.row > 0){
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;//cell的右边有一个小箭头，距离右边有十几像素；
    }
    
    cell.backgroundColor = [UIColor whiteColor];
    return  cell;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField;
{
    [textField resignFirstResponder];
    return YES;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self.view endEditing:YES];
    UITableViewCell *cell = (UITableViewCell *)[self.tableView cellForRowAtIndexPath:_indexPath];
    [_pickview remove];
    _indexPath=indexPath;
    if (indexPath.row == 1) {
        _pickview=[[ZHPickView alloc] initPickviewWithArray:@[@"男",@"女"] isHaveNavControler:NO];
        _pickview.delegate=self;
        [_pickview show];
    }else if (indexPath.row == 2){
        NSString *currentDateString = @"1990-01-01";
        NSDateFormatter* dateFormater = [[NSDateFormatter alloc]init];
        [dateFormater setDateFormat:@"yyyy-MM-dd"];
        NSDate *currentDate = [dateFormater dateFromString:currentDateString];
        _pickview=[[ZHPickView alloc] initDatePickWithDate:currentDate datePickerMode:UIDatePickerModeDate isHaveNavControler:NO];
        _pickview.delegate=self;
        [_pickview show];
    }else if (indexPath.row == 3){
        _pickview=[[ZHPickView alloc] initPickviewWithPlistName:@"city" isHaveNavControler:NO];
        _pickview.delegate=self;
        [_pickview show];
    }else if (indexPath.row == 4){
        UserDateEditSeriesViewController *EditSeriesVC = [[UserDateEditSeriesViewController alloc]init];
        EditSeriesVC.Delegate = self;
        if (self.gender == 1) {
            EditSeriesVC.titleArr = @[@"小鲜肉系",@"高冷型男系",@"幽默逗比系",@"知心暖男系",@"霸道总裁系",@"百变全能系"];
        }else{
            EditSeriesVC.titleArr = @[@"软妹萝莉系",@"温柔依人系",@"阳光治愈系",@"知性御姐系",@"傲娇女王系",@"百变全能系"];
        }
        EditSeriesVC.nowSeriesStr = cell.detailTextLabel.text;
        [self.navigationController pushViewController:EditSeriesVC animated:YES];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [titleArr count];
}

//选择控件返回内容后赋值
-(void)toobarDonBtnHaveClick:(ZHPickView *)pickView resultString:(id )resultString{
    NSString * str = [[NSString alloc]init];
    if (_indexPath.row == 1) {
        str = [NSString stringWithFormat:@"%@",resultString];
        if ([str isEqualToString:@"男"]) {
            self.gender = 1;
        }else{
            self.gender = 2;
        }
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:4 inSection:0];
        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        cell.detailTextLabel.text = @"";
        [self.tableView reloadData];
    }else if (_indexPath.row == 2){
        NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        str = [dateFormatter stringFromDate:resultString];
        jobdate = resultString;
    }else if (_indexPath.row == 3){
        self.location = [NSArray arrayWithArray:resultString];
        for (int i = 0 ; i < [resultString count]; i++) {
            if (i == [resultString count]-1) {
                str = [str stringByAppendingString:[NSString stringWithFormat:@"%@",resultString[i]]];
            }else{
                str = [str stringByAppendingString:[NSString stringWithFormat:@"%@ ",resultString[i]]];
            }
        }
    }
    
    
    UITableViewCell *cell = (UITableViewCell *)[self.tableView cellForRowAtIndexPath:_indexPath];
    cell.detailTextLabel.text = str;
}

//修改系列返回内容后赋值
-(void)UserSeriesString:(NSString *)str
{
    UITableViewCell *cell = (UITableViewCell *)[self.tableView cellForRowAtIndexPath:_indexPath];
    cell.detailTextLabel.text = str;
    
}

-(void)backgroundPan:(id)sender
{
    FSMediaPicker *mediaPicker = [[FSMediaPicker alloc] init];
    mediaPicker.mediaType = FSMediaTypePhoto;
    mediaPicker.editMode = FSEditModeCircular;
    mediaPicker.delegate = self;
    [mediaPicker showFromView:self.view];
    
}
//压缩图片
+ (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
//    //创建一个图形上下文形象
//    UIGraphicsBeginImageContext(newSize);
//    // 告诉旧图片画在这个新的环境,所需的
//    // new size
//    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
//    //获取上下文的新形象
//    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
//    // 结束上下文
//    UIGraphicsEndImageContext();
//    return newImage;
    CGFloat width = CGImageGetWidth(image.CGImage);
    CGFloat height = CGImageGetHeight(image.CGImage);
    
    float verticalRadio = newSize.height*1.0/height;
    float horizontalRadio = newSize.width*1.0/width;
    
    float radio = 1;
    if(verticalRadio>1 && horizontalRadio>1)
    {
        radio = verticalRadio > horizontalRadio ? horizontalRadio : verticalRadio;
    }
    else
    {
        radio = verticalRadio < horizontalRadio ? verticalRadio : horizontalRadio;
    }
    
    width = width*radio;
    height = height*radio;
    
    int xPos = (newSize.width - width)/2;
    int yPos = (newSize.height-height)/2;
    
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(newSize);
    //下面4行代码可以把图片背景变为黑色
     CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, [[UIColor blackColor] CGColor]);
         CGRect rect = CGRectMake(0.0f, 0.0f, newSize.width, newSize.height);
        CGContextFillRect(context, rect);
    
    // 绘制改变大小的图片
    [image drawInRect:CGRectMake(xPos, yPos, width, height)];
    
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    
    // 返回新的改变大小后的图片
    return scaledImage;
}
- (void)mediaPicker:(FSMediaPicker *)mediaPicker didFinishWithMediaInfo:(NSDictionary *)mediaInfo
{
    UIImage *image;
    if(mediaPicker.editMode == FSEditModeCircular){
        [self.userAvatarImg setImage:mediaInfo.editedImage];
        image = mediaInfo.editedImage;
    }else {
        [self.userAvatarImg setImage:mediaInfo.originalImage];
        image = mediaInfo.originalImage;
    }
    CGSize size = CGSizeMake(600  , 600);
    
    image = [InitDataViewController imageWithImageSimple:image scaledToSize:size];
    float kCompressionQuality = 0.3;
    NSData *imgData = UIImageJPEGRepresentation(image, kCompressionQuality);
    
    
    self.avatarFile = [AVFile fileWithName:@"photo.jpg" data:imgData];
    [self.avatarFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        [HUD hideFromViewAnimated:YES];
        if (succeeded) {
            bool_headimage =  YES;
            NSLog(@"save avatar succeed");
            MPUser *currentUser = [MPUser currentUser];
            currentUser.avatar = self.avatarFile;
            [currentUser saveInBackgroundWithBlock: ^(BOOL succeed, NSError *error){
                if (succeed) {
                }
                
            }];
            NSMutableArray *galleryImgs = [NSMutableArray array];
            [galleryImgs addObject:self.avatarFile];
            // 获取相册内容
            AVQuery *galleryQuery = [MPGallery query];
            [galleryQuery whereKey:@"belong_to" equalTo:currentUser];
            [galleryQuery includeKey:@"images"];
            [galleryQuery getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
                MPGallery *g = (MPGallery*)object;
                if (!g) {
                    // 找不到,创建新相册
                    g = [MPGallery object];
                } else {
                }
                g.belong_to = [MPUser currentUser];
                g.images = galleryImgs;
                [g saveInBackground];
            }];
        } else {
            NSLog(@"save avatar failed");
            bool_headimage =  NO;
            [HUD Prompt:@"保存头像失败,请检查网络再重试"];
            self.avatarFile = nil;
        }
        
    }];
    [HUD setOnViewWithTitle:nil animated:YES];
}



- (BOOL)verifySubmitInfo:(NSString *)nickname gender:(NSInteger)gender birthday:(NSDate *)birthday belong:(NSString*)belong avatar:(AVFile *)avatarFile{
    
    if (!nickname || [nickname isEqualToString:@""]) {
        [HUD Prompt:@"请填写昵称"];
        return NO;
    } else if ([nickname length] > 16) {
        [HUD Prompt:@"昵称不能超过16个字"];
        return NO;
    } else if (!avatarFile) {
        [HUD Prompt:@"请上传头像"];
        return NO;
    } else if (gender == 0) {
        [HUD Prompt:@"请选择性别"];
        return NO;
    } else if (!birthday) {
        [HUD Prompt:@"请选择生日"];
        return NO;
    } else if ([belong length] < 1){
        [HUD Prompt:@"请选择你属于的类型"];
        return NO;
    }
    return YES;
}

-(void)rightItem
{
    
    
    UITableViewCell *gendercell = (UITableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    UITableViewCell *belongcell = (UITableViewCell *)[self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:4 inSection:0]];
    
    
    if ([gendercell.detailTextLabel.text isEqual:@"男"]) {
        self.gender = 1;
    }else{
        self.gender = 2;
    }
    
    [self.view endEditing:YES];
    // 获取用户填写的信息
    self.nickname = userName.text;  // 昵称
    
    NSString *str = self.nickname;
    if (str == nil||str == NULL|| [str isKindOfClass:[NSNull class]]||[[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length]==0) {
        [HUD Prompt:@"昵称不能全为空格"];
        return;
    }
    
    NSDate *birthday = jobdate;
    NSString *district = self.location[0];
    NSString *city = self.location[1];
    NSString *belong   = belongcell.detailTextLabel.text;
    if (bool_headimage == YES) {
        // 校验数据
        BOOL isDataValid = [self verifySubmitInfo:self.nickname gender:self.gender birthday:birthday belong:belong avatar:self.avatarFile];
        if (isDataValid) {
            // 保存数据
            MPUser *currentUser = [MPUser currentUser];
            currentUser.nickname = self.nickname;
            currentUser.birthday = birthday;
            currentUser.gender = self.gender;
//            currentUser.location_province = district;
//            currentUser.location_city = city;
//            currentUser.belong = belong;
//            
//            // 其他初始化数据
//            currentUser.status = MPUserStatus_NORMAL;
//            currentUser.level = MPUserLevel_0;
//            currentUser.intro = @"我们虚拟恋爱吧";
            currentUser.isUserInited = YES;  // 标识已初始化
            
            currentUser.avatar = self.avatarFile;
            
            // 后台线程保存资料并跳转
            [currentUser saveInBackgroundWithBlock: ^(BOOL succeed, NSError *error){
                // 停止转菊花
                [HUD hideFromViewAnimated:YES];
                if (!error) {
                    
                    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
                    [appDelegate loginToEasemob];
                    [self dismissViewControllerAnimated:YES completion:nil];
                    [self.navigationController popViewControllerAnimated:YES];
                } else {
                    // 提示保存失败
                    NSString *msg = @"保存个人资料失败,请重试";
                    [HUD Prompt:msg ];
                }
            }];
            // 页面开始转菊花
            [HUD setOnViewWithTitle:nil animated:YES];
        }
        
    }else{
        [HUD Prompt:@"请上传用户头像"];
        [HUD hideFromViewAnimated:YES];
    }
    
    
}

- (NSString *) md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    if ([self isViewLoaded]&&!self.view.window) {
        self.view = nil;
    }
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
